<template>
  <el-upload
    ref="uploader"
    v-if="drag"
    class="upload-file"
    drag
    :action="path || action"
    :accept="accept"
    :headers="headers"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="onSuccess"
    :before-upload="beforeUpload"
    :before-remove="beforeRemove"
    :limit="limit"
    :file-list="fileList"
    :on-exceed="handleExceed"
    v-bind="$attrs"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">
      将文件拖到此处，或
      <em>点击上传</em>
    </div>
    <div v-if="tips" slot="tip" class="el-upload__tip">{{ desc }}</div>
  </el-upload>
  <el-upload
    v-else
    ref="uploader"
    class="upload-file"
    :accept="accept"
    :action="path || action"
    :headers="headers"
    :on-preview="handlePreview"
    :on-change="handleChange"
    :on-remove="handleRemove"
    :on-success="onSuccess"
    :before-upload="beforeUpload"
    :before-remove="beforeRemove"
    :limit="limit"
    :file-list="fileList"
    :multiple="limit > 1"
    :on-exceed="handleExceed"
    v-bind="$attrs"
  >
    <el-button
      :size="btnProps.size || 'small'"
      :type="btnProps.type || 'primary'"
      v-bind="btnProps"
      >{{ btnText }}</el-button
    >
    <div v-if="tips" slot="tip" class="el-upload__tip">{{ desc }}</div>
  </el-upload>
</template>

<script>
/*
"orderAccessorys":[{
"fileFormat": "string",//类型
"fileSize": 0,
"site": "string",
}]
*/
import { mapState } from "vuex";
import transferMixin from "./transferMixin";
export default {
  name: "upload-file",
  mixins: [transferMixin],
  props: {
    drag: {
      type: Boolean,
      default: false
    },
    url: {
      type: String,
      default: "/"
    },
    path: {
      type: String,
      default: ""
    },
    btnText: {
      type: String,
      default: "点击上传"
    },
    btnProps: {
      type: Object,
      default: () => ({})
    },
    tips: {
      type: Boolean,
      default: true
    },
    maxSize: {
      type: Number,
      default: 20
    },
    accept: {
      type: String,
      default: ".png,.jpg,.jpeg,.bmp,.rar,.zip,.doc,.docx,.pdf,.xlsx,.xls"
    },
    descText: {
      type: String,
      default: undefined
    },
    limit: {
      type: Number,
      default: 3
    },
    clear: {
      type: Boolean,
      default: true
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    clear(val) {
      if (!val) {
        this.clearFiles();
      }
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token
    }),
    action() {
      return process.env.VUE_APP_API_PREFIX_URL + this.url;
    },
    // token
    headers() {
      return {
        Authorization: `Bearer ${this.token}`
      };
    },
    desc() {
      return (
        this.descText ||
        `支持格式：${this.accept} ，单个文件不能超过${this.maxSize}MB，最多上传个数：${this.limit} 。`
      );
    }
  },
  methods: {
    clearFiles() {
      this.fileList = [];
      this.$refs.uploader.clearFiles();
    },
    submitUpload() {
      this.$refs.uploader.submit();
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.fileChange();
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleChange(file, fileList) {},
    handleExceed(files, fileList) {
      this.handleWarning(`只能选择 ${this.limit} 个文件`);
    },
    beforeUpload(file) {
      const { size, type, name } = file;
      return this.checkFileType(name) && this.checkFileSize(size);
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    onSuccess(res, file, fileList) {
      // console.log(fileList);
      const { msg, status, code } = res;
      if (code === 0) {
        this.$emit("success");
        this.handleSuccess("上传成功");
        this.clearFiles();
        return;
      }
      this.fileList = fileList;
      this.fileChange();
      if (status === 0) {
        this.$emit("success");
        this.handleSuccess(msg);
      } else {
        this.$message({
          type: "error",
          message: msg,
          duration: 8000,
          showClose: true
        });
      }
    },
    checkFileType(name) {
      let t = name.substring(name.lastIndexOf(".")).toLowerCase();
      if (
        this.accept &&
        this.accept.split(",").filter(i => i.trim() === t).length === 0
      ) {
        this.handleWarning(`上传文件只能是 ${this.accept} 格式!`);
        return false;
      }
      return true;
    },
    checkFileSize(size) {
      if (size > 1024 * 1024 * this.maxSize) {
        this.handleWarning(`上传文件大小不能超过 ${this.maxSize} M!`);
        return false;
      }
      return true;
    }
  }
};
</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 1.2;
  margin: 0;
  color: #e6a23c;
}
</style>
